#!/usr/bin/perl
# isbn-groups.js maker
use strict;
use warnings;

use LWP::UserAgent;
use JSON;

my $resp = LWP::UserAgent->new(env_proxy => 1)->get(
  'http://www.isbn-international.org/converter/ranges.js');
$resp->is_success
  or die $resp->message;

my $js = $resp->content;
my $v = sprintf '%04d%02d%02d', reverse $js =~ /-----\r?\n(\d{1,2}).(\d{1,2}).(\d{4});/;

my $areas = {};
$areas->{$1} = {
    name => $2,
    ranges => [map { [split /-/] } split /;/, $3]
  }
  while ($js =~ /gi\.area(\d+)\.text\s*=\s*"(.+)";?\r?\ngi\.area\d+\.pubrange\s*=\s*"([\d\-;]*)";?/g);

my $json = JSON->new;
my $g = $json->canonical->encode($areas);
$g =~ s/^{/$&\n  /g;
$g =~ s/}}$/\n  }\n}/g;
$g =~ s/"ranges"/\n    $&/g;
$g =~ s/:{/$&\n    /g;
$g =~ s/:/$& /g;
$g =~ s/,([\["])/, $1/g;
$g =~ s/},/\n  $&\n /g;

print << "DATA"
// isbn-groups.js
// generated by mkgroups.pl
if (typeof ISBN == 'undefined')
  var ISBN = {};

// referred: http://www.isbn-international.org/converter/ranges.htm
// frequently, you need to update the following table. what a nice specification!
ISBN.GROUPS_VERSION = '$v';
ISBN.GROUPS = $g;
DATA
